package com.example.administrator.testdagger.design.proxy;

import android.util.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * com.example.administrator.testdagger.design.proxy
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/8/3 14:00
 * @see com.example.administrator.testdagger.design.proxy
 */
public class LogProxy implements InvocationHandler {

    Calculate mCaculate;

    public LogProxy(Calculate calculate) {
        mCaculate = calculate;
    }

    public Object bind() {
        return Proxy.newProxyInstance(mCaculate.getClass().getClassLoader(),
                mCaculate.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        //打印日志
        Log.d("WJQ", "[before] The method " + methodName + " begins with " + Arrays.asList(args));

        //调用目标方法
        Object result = null;

        try {
            //前置通知
            result = method.invoke(mCaculate, args);
            //返回通知, 可以访问到方法的返回值
        } catch (NullPointerException e) {
            e.printStackTrace();
            //异常通知, 可以访问到方法出现的异常
        }

        //后置通知. 因为方法可以能会出异常, 所以访问不到方法的返回值

        //打印日志
        Log.d("WJQ", "[after] The method ends with " + result);

        return result;
    }
}
